package otSpaces;

import java.math.BigInteger;

public class OtSpaceFunctions {

	public static final String NUMBER_REGEX;
	public static final String SPACE_REGEX;
	public static final String TOPIC_CHANNEL_REGEX;

	static {
		SPACE_REGEX = "[a-zA-Z0-9\\.]+";
		NUMBER_REGEX = "\\-?\\d+";
		TOPIC_CHANNEL_REGEX = "ot.topicChannel>" + SPACE_REGEX + ">"
				+ NUMBER_REGEX;
	}

	/**
	 * Folds an object's hashCode into 1 byte
	 * 
	 * @param object
	 * @return
	 */
	public static byte foldHashCode(Object object) {
		final int hashCode = object.hashCode();

		return (byte) ((hashCode & 0x000000ff) ^ ((hashCode & 0x0000ff00) >> 8)
				^ ((hashCode & 0x00ff0000) >> 16) ^ ((hashCode & 0xff000000) >> 24));
	}

	public static boolean isOtTopicSpaceName(String topicChannelName) {
		return topicChannelName.matches(TOPIC_CHANNEL_REGEX);
	}

	/**
	 * 
	 * @param bigInteger
	 * @return
	 */
	public static String topicSpaceNameCreate(BigInteger bigInteger, String name) {

		if (!name.matches(SPACE_REGEX)) {
			throw new IllegalArgumentException(
					"Name is not a proper space name (sorry)");
		}

		final String withBI = TOPIC_CHANNEL_REGEX.replace(NUMBER_REGEX,
				bigInteger.toString());

		final String ret = withBI.replace(SPACE_REGEX, name);

		assert ret.matches(TOPIC_CHANNEL_REGEX);

		return ret;
	}

	public static String topicSpaceNameGet(String topicChannelName) {
		final String first = topicChannelName.substring(topicChannelName
				.indexOf('>') + 1);

		return first.substring(0, first.indexOf('>'));
	}

}
